//
//  EDSCommunityPlayerViewController.m
//  DrivieSchoolStudents
//
//  Created by TangBin on 2019/5/24.
//  Copyright © 2019 班文政. All rights reserved.
//

#import "EDSCommunityPlayerViewController.h"
#import "EDSPlayerView.h"
#import "EDSPlayTransport.h"

@interface EDSCommunityPlayerViewController () <EDSPlayTransportDelegate>

@property (nonatomic, strong) EDSPlayerView *playerView;

@property (nonatomic, strong) AVPlayer *player; ///< 播放器对象

@property (nonatomic, strong) AVPlayerItem *playerItem;

@property (nonatomic, strong) id timeObserver; ///< 视频播放时间观察者

@property (nonatomic, weak) id<EDSPlayTransport> transport;

@property (nonatomic, assign) BOOL isFetchTotalDuration; ///< 是否获取了视频长度

@property (nonatomic, assign) NSTimeInterval bufferTime;

@property (nonatomic, assign) BOOL isTapPlayer; ///< 是否点击播放了

- (void)initWithPlayerView;

@end

@implementation EDSCommunityPlayerViewController

- (void)dealloc
{
    NSLog(@"%s", __func__);
    [self removeVideoNotication];
    [self removeVideoTimerObserver];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SVProgressHUDDidReceiveTouchEventNotification object:nil];
}

- (void)initWithVar
{
    [super initWithVar];
    
    self.isFetchTotalDuration = NO;
    
    // http://static.tripbe.com/videofiles/20121214/9533522808.f4v.mp4
    // http://111.39.245.156:8087/files/lexiang/community/dynamic/video/2019-05-23/1558602277756_62195.mp4
//    self.videoUrl = [NSURL URLWithString:@"http://static.tripbe.com/videofiles/20121214/9533522808.f4v.mp4"];
    
    self.playerItem = [[AVPlayerItem alloc] initWithURL:self.videoUrl];
    self.player = [[AVPlayer alloc] initWithPlayerItem:self.playerItem];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleNotification:)
                                                 name:SVProgressHUDDidReceiveTouchEventNotification
                                               object:nil];
}

- (void)initWithNavBar
{
    [super initWithNavBar];
    
    [self initWithBackButton];
}

- (void)initWithSubView
{
    [super initWithSubView];
    
    [self initWithPlayerView];
    
    self.playerView.player = self.player;
    
    [self addVideoKVO];
    [self addVideoTimerObserver];
    [self addVideoNotication];
    
}

- (void)handleNotification:(NSNotification *)notification
{
    [SVProgressHUD dismiss];
    [self.playerView.overlayView loadStop];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    [[UIApplication sharedApplication] setStatusBarHidden:YES];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
//    [[UIApplication sharedApplication] setStatusBarHidden:YES];
//    prefersStatusBarHidden
}

- (BOOL)prefersStatusBarHidden
{
//    NSLog(@"frame=%@", NSStringFromCGRect(self.view.frame));
    return YES;
}

- (void)viewWillDisappear:(BOOL)animated
{
    
    [super viewWillDisappear:animated];
}

- (void)initWithPlayerView
{
    if (!_playerView)
    {
        CGRect frame = self.view.bounds;
        _playerView = [[EDSPlayerView alloc] initWithFrame:frame];
        _playerView.backgroundColor = [UIColor blackColor];
        self.transport = _playerView.transport;
        self.transport.isBuffering = YES; // 初始化的时候，就开始缓冲
        self.transport.delegate = self;
        [self.view addSubview:_playerView];
    }
}

#pragma mark - KVO
- (void)addVideoKVO
{
    // RAC 自动实现了KVO的销毁工作
    @weakify(self);
    // 监听status属性 注意AVPlayer也有一个status属性，通过监控它的status也可以获的播放状态
    [RACObserve(self.playerItem, status) subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [self playerItemStatusChange:[x integerValue]];
    }];
    
    // 监听loadedTimeRanges  监控网络加载情况属性
    [RACObserve(self.playerItem, loadedTimeRanges) subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [self playerItemLoadedTimeRangesChange];
    }];
    
    // 监听播放的区域缓存是否为空
    [RACObserve(self.playerItem, playbackBufferEmpty) subscribeNext:^(id  _Nullable x) {
        
    }];
    
    // 缓存可以播放的时候调用
    [RACObserve(self.playerItem, playbackLikelyToKeepUp) subscribeNext:^(id  _Nullable x) {
        
    }];
}

- (void)addVideoTimerObserver
{
    // 监听播放状态
    @weakify(self);
    self.timeObserver = [self.playerView.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        @strongify(self);
        NSTimeInterval currentTime = CMTimeGetSeconds(time);
        NSLog(@"获取当前播放时间=%f", currentTime);
        self.transport.currentPlayTime = currentTime; // 当前已经播放的时间
        
        
    }];
}

- (void)addVideoNotication
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movieJummped:) name:AVPlayerItemTimeJumpedNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movieStalle:) name:AVPlayerItemPlaybackStalledNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bakkgroundPauseMoive:) name:UIApplicationDidEnterBackgroundNotification object:nil];
    
}

- (void)removeVideoNotication
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemTimeJumpedNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemPlaybackStalledNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)removeVideoTimerObserver
{
    [self.playerView.player removeTimeObserver:_timeObserver];
}

/**
 *  可用的播放时长(缓冲的时长)
 *
 */
- (NSTimeInterval)availableBufferTime
{
    NSArray *loadTimeRanges = [[self.player currentItem] loadedTimeRanges];
    
    //获取缓冲区域
    CMTimeRange range = [loadTimeRanges.firstObject CMTimeRangeValue];
    
    NSTimeInterval startTime = CMTimeGetSeconds(range.start);
    
    NSTimeInterval duration = CMTimeGetSeconds(range.duration);
    
    return startTime + duration;
}

#pragma mark - KVO 调用的函数
/**
 AVPlayerItem 对象的status属性改版

 @param status status description
 */
- (void)playerItemStatusChange:(NSInteger)status
{
    NSLog(@"status=%zd", status);
    if (status == AVPlayerItemStatusReadyToPlay)
    {// 表示可以播放了
        NSLog(@"准备完成，可以播放了");
        @weakify(self);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            @strongify(self);
            if (self.isTapPlayer)
            {
                [self play];
                [SVProgressHUD dismiss];
            }
        });
        
    }
    else if (status == AVPlayerItemStatusFailed)
    {
        NSLog(@"AVPlayerItemStatusFailed");
    }
    else
    {
        NSLog(@"AVPlayerItemStatusUnknown");
    }
}

/**
 视频缓冲
 */
- (void)playerItemLoadedTimeRangesChange
{
    AVPlayerItem *item = self.playerView.player.currentItem;
    // 可用的播放时长(缓冲的时长)
    self.bufferTime = [self availableBufferTime];
    if (!self.isFetchTotalDuration)
    {// 还没有获取视频长度
        // 获取视频的总长度
        NSTimeInterval totalDuration = CMTimeGetSeconds(item.duration);
        self.transport.durationTime = totalDuration;
        self.isFetchTotalDuration = YES;
        NSLog(@"获取视频长度=%f", totalDuration);
    }
    
    if (self.transport.currentPlayTime <= self.transport.durationTime - 7)
    {
        // 如果缓冲不够
        if (self.bufferTime <= self.transport.currentPlayTime + 5)
        {// 换从不够，进行缓冲
            self.transport.isBuffering = YES;
            NSLog(@"正在缓存中");
            if (self.isTapPlayer)
            {
                [SVProgressHUD show];
            }
        }
        else
        {
            self.transport.isBuffering = NO;
            NSLog(@"缓冲完成22");
//            if (self.isTapPlayer)
//            {
//                [self play];
//                [SVProgressHUD dismiss];
//            }
            
            @weakify(self);
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                @strongify(self);
                if (self.isTapPlayer)
                {
                    [self play];
                    [SVProgressHUD dismiss];
                }
            });
            
        }
    }
    else
    {
        NSLog(@"缓冲完成11");
        self.transport.isBuffering = NO;
//        if (self.isTapPlayer)
//        {
//            [self play];
//            [SVProgressHUD dismiss];
//        }
        @weakify(self);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            @strongify(self);
            if (self.isTapPlayer)
            {
                [self play];
                [SVProgressHUD dismiss];
            }
        });
    }
    self.transport.currentBufferTime = self.bufferTime;
}

#pragma mark - 通知

/**
 视频播放完成

 @param note play description
 */
- (void)moviePlayDidEnd:(NSNotification *)note
{
    NSLog(@"视频播放完成。");
    self.isFetchTotalDuration = NO;
    [self.transport bgPause];
    @weakify(self);
    [self.player seekToTime:kCMTimeZero completionHandler:^(BOOL finished) {
        @strongify(self);
        self.transport.currentPlayTime = 0;
        self.transport.currentBufferTime = 0;
        self.transport.durationTime = 0;
    }];
}

- (void)movieJummped:(NSNotification *)noti
{
    NSLog(@"movieJummped");
}

- (void)movieStalle:(NSNotification *)noti
{
    NSLog(@"movieStalle");
}

- (void)bakkgroundPauseMoive:(NSNotification *)noti
{
    NSLog(@"bakkgroundPauseMoive");
    [self.transport bgPause];
    [self pause];
}

#pragma mark - EDSPlayTransportDelegate

- (void)play
{
    self.isTapPlayer = YES;
    if (self.transport.isBuffering || self.playerItem.status != AVPlayerItemStatusReadyToPlay)
    {// 如果正在缓冲，就显示加载提示
        NSLog(@"正在缓冲---------");
        [SVProgressHUD show];
    }
    else
    {// 缓冲完成，开始播放
        NSLog(@"缓冲完成---------");
        [self.playerView.player play];
    }
}

- (void)pause
{
    self.isTapPlayer = NO;
    [self.playerView.player pause];
}

- (void)stop
{
    self.isTapPlayer = NO;
    self.isFetchTotalDuration = NO;
    [self moviePlayDidEnd:nil];
}

- (void)back
{
    [self stop];
    [self dismissViewControllerAnimated:NO completion:nil];
}

@end
